/*
 * This file is part of "Sorting Thoughts" project.
 *
 * Copyright (c) 2009 Hendrik Ebel
 * All Rights Reserved.
 *
 * Please visit http://code.google.com/p/sorting-thoughts/ for more information.
 *
 * --LICENSE NOTICE--
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 3
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; If not, see <http://www.gnu.org/licenses/>.
 * --LICENSE NOTICE--
 */
function PreferencesAssistant(){
}

PreferencesAssistant.prototype.setup = function(){
    Mojo.Log.info("#######################################");
    Mojo.Log.info("Setup preferences scene");
    Mojo.Log.info("#######################################");
	
    // enable new by shake pref
    this.controller.setupWidget("enableNewByShakeToggle", {}, this.enableNewByShakeToggleModel = {
        value: SortingThoughts.enableNewByShake
    });
    
    this.changeEnableNewByShakeHandler = this.changeEnableNewByShake.bindAsEventListener(this);
    this.controller.listen("enableNewByShakeToggle", Mojo.Event.propertyChange, this.changeEnableNewByShakeHandler);
    
    // show date pref
    this.controller.setupWidget("enableShowDateToggle", {}, this.enableShowDateToggleModel = {
        value: SortingThoughts.showDate
    });
    
    this.changeEnableShowDateHandler = this.changeEnableShowDate.bindAsEventListener(this);
    this.controller.listen("enableShowDateToggle", Mojo.Event.propertyChange, this.changeEnableShowDateHandler);
	
	// app lock pref
    this.controller.setupWidget("enableAppLockToggle", {}, this.enableAppLockToggleModel = {
        value: SortingThoughts.enableAppLock
    });
    
    this.changeEnableAppLockHandler = this.changeEnableAppLock.bindAsEventListener(this);
    this.controller.listen("enableAppLockToggle", Mojo.Event.propertyChange, this.changeEnableAppLockHandler);
	
	// Setup App Menu 
    this.controller.setupWidget(Mojo.Menu.appMenu, this.attributes = {
		omitDefaultItems: true
		}, this.model = {
		visible: false	
		}
	);
	
	// add command menu
	if (SortingThoughts.isTouchPad()) {
		this.controller.setupWidget(Mojo.Menu.commandMenu, undefined, {
			items: [{
				label: 'Back',
				command: 'backToOverview',
				icon: 'back'
			}]
		});
	}
	
};

PreferencesAssistant.prototype.activate = function(event) {
	this.getLastSyncDate();
};

PreferencesAssistant.prototype.deactivate = function(event) {
    SortingThoughts.Cookie.storeCookie();
};

PreferencesAssistant.prototype.cleanup = function(event){
	Mojo.Log.info("#######################################");
    Mojo.Log.info("Clean up preferences scene");
    Mojo.Log.info("#######################################");
    this.controller.stopListening("enableNewByShakeToggle", Mojo.Event.propertyChange, this.changeEnableNewByShakeHandler);
    this.controller.stopListening("enableShowDateToggle", Mojo.Event.propertyChange, this.changeEnableShowDateHandler);
	this.controller.stopListening("enableAppLockToggle", Mojo.Event.propertyChange, this.changeEnableAppLockHandler);
};

PreferencesAssistant.prototype.handleCommand = function(event){
    if (event.type == Mojo.Event.command) {
        switch (event.command) {
			case 'backToOverview':
				SortingThoughts.Cookie.storeCookie();
				event.stopPropagation();
				this.controller.stageController.popScene();
				break;
        }
    }
};

PreferencesAssistant.prototype.changeEnableNewByShake = function(event){
    SortingThoughts.enableNewByShake = event.value;
};

PreferencesAssistant.prototype.changeEnableShowDate = function(event){
    SortingThoughts.showDate = event.value;
};

PreferencesAssistant.prototype.changeEnableAppLock = function(event){
	if (event.value) {
		// open app lock dialog
		Mojo.Log.info("open activate dialog");
		this.controller.showDialog({
			template: 'preferences/set-applock-dialog-scene',
			assistant: new SetAppLockDialog(this),
			preventCancel: true
		});
		
	} else {
		// remove lock
		// before user must enter the current password
		Mojo.Log.info("open disable dialog");
		this.controller.showDialog({
			template: 'preferences/remove-applock-dialog-scene',
			assistant: new RemoveAppLockDialog(this),
			preventCancel: true
		});
	} 
	
	this.controller.modelChanged(this.enableAppLockToggleModel, this);
};

PreferencesAssistant.prototype.getLastSyncDate = function(){

    if (!SortingThoughts.dao.db) {
        Mojo.Log.error("Could not access sorting thoughts database");
    } else {
        try {
			Mojo.Log.info("select sync");
            var sql = "SELECT * FROM 'sync';";
            SortingThoughts.dao.db.transaction((function(transaction){
                transaction.executeSql(sql, [], this.selectQueryDataHandler.bind(this), this.dbErrorHandler.bind(this));
            }).bind(this));
        } catch (e) {
            Mojo.Log.error("Sorting Thoughts DB Error: " + e);
        }
        
    }
};

PreferencesAssistant.prototype.selectQueryDataHandler = function(transaction, results){
    try {
        this.controller.get('lastSync').innerHTML = $L("Last Sync");

        for (var i = 0; i < results.rows.length; i++) {
            var row = results.rows.item(i);
            var date = row['allLastSyncDate'];
            
            //update widget
			Mojo.Log.info("row " + row);
			Mojo.Log.info("sync date " + this.formatDate(date));
    		this.controller.get('lastSyncValue').innerHTML = this.formatDate(date);
			
            break;
        }
		
		if (results && results.rows.length == 0) {
			this.controller.get('lastSyncValue').innerHTML = $L("not executed");
		}
        
    } catch (e) {
         Mojo.Log.error("Query Handler Error: " + e);
    }
};

PreferencesAssistant.prototype.dbErrorHandler = function(transaction, error){
    Mojo.Log.error("Sorting Thoughts DB Error: " + error.message);
    Mojo.Controller.errorDialog(error.message, this.controller.window);
};

PreferencesAssistant.prototype.formatDate = function(rawDate){
	if (rawDate) {
		var cTime = new Date(parseFloat(rawDate));
		return Mojo.Format.formatDate(cTime, "short");
	} else {
		return $L("not executed");
	}
};
